package com.tanhua.mongo.api;

import com.tanhua.api.VideoApi;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.mongo.util.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    //保存小视频数据
    @Override
    public String save(Video video) {
        //设置vid唯一标识
        video.setVid(idWorker.getNextId("video"));

        //保存
        mongoTemplate.save(video);

        //发那会小视频主键
        return video.getId().toHexString();
    }

    //根据vids 查询推荐视频
    @Override
    public List<Video> findByVids(List<Long> vids) {
        return mongoTemplate.find(Query.query(
                Criteria.where("vid").in(vids)
        ), Video.class);
    }

    //分页查询 按照发布时间倒序排序
    @Override
    public List<Video> findByPage(int page, Integer pagesize) {
        return mongoTemplate.find(
                new Query()
                        .skip((page - 1) * pagesize)
                        .limit(pagesize)
                        .with(Sort.by(Sort.Order.desc("created")))
                , Video.class);
    }

    //根据用户id 分页查询小视频数据
    @Override
    public PageResult findPageByUid(Long uid, Integer page, Integer pagesize) {
        //1 创建查询的条件  用户id
        Query query = Query.query(Criteria.where("userId").is(uid));

        //2 查询符合条件的总记录数
        long count = mongoTemplate.count(query, Video.class);

        //3 设置分页参数
        query.skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4 执行分页查询
        List<Video> videoList = mongoTemplate.find(query, Video.class);

        //5 封装分页对象  返回结果
        return new PageResult(page, pagesize, (int) count, videoList);
    }
}
